import {PageContainer, ProCard} from '@ant-design/pro-components';
import {Input, message, Tabs, Tag} from 'antd';
import React, {useCallback, useEffect, useState} from 'react';
import {
  getInterfaceInfoDetailByIdUsingGet,
  interfaceInfoCallUsingPost,
} from '@/services/sutongapi-backend/interfaceInfoController';
import {useParams} from '@@/exports';
import JsonInput from '@/components/JsonInput';
import moment from 'moment';

/**
 * 计算初始化请求数据json
 */
let requestParamsInit = '';
let requestHeadersInit = '';
const computeInitValue = (data?: API.InterfaceParamVo[]): string => {
  if (data === undefined || data === null) {
    return '';
  }
  let requestParamsObj: any = {};
  data?.forEach((item) => {
    if (item.fieldType === 'object') {
      requestParamsObj[item.name!] = JSON.parse(computeInitValue(item.children));
    } else if (item.fieldType === 'number') {
      requestParamsObj[item.name!] = 0;
    } else if (item.fieldType === 'array') {
      requestParamsObj[item.name!] = [];
    } else if (item.fieldType === 'boolean') {
      requestParamsObj[item.name!] = true;
    } else if (item.fieldType === 'date') {
      requestParamsObj[item.name!] = moment().format('yyyy-MM-dd HH:mm:ss');
    } else {
      requestParamsObj[item.name!] = '';
    }
  });
  return JSON.stringify(requestParamsObj, null, '\t');
};

const AdvancedSearch: React.FC = () => {
  const params = useParams();
  const [verifyRes, setVerifyRes] = useState(true);
  const [isShownRequest, setIsShownRequest] = useState(false);
  const [isShownResponse, setIsShownResponse] = useState(false);
  const [data, setData] = useState<API.InterfaceInfoDetail>();

  // Tab
  const [userRequestParams, setUserRequestParams] = useState<string>('');
  const onRequestParamsChange = useCallback((val: string) => {
    setUserRequestParams(val);
  }, []);
  const [userRequestHeaders, setUserRequestHeaders] = useState<string>('');
  const onRequestHeadersChange = useCallback((val: string) => {
    setUserRequestHeaders(val);
  }, []);

  const [userResponseParams, setUserResponseParams] = useState<string>('');
  const onResponseParamsChange = useCallback((val: string) => {
    setUserResponseParams(val);
  }, []);
  const [userResponseHeaders, setUserResponseHeaders] = useState<string>('');
  const onResponseHeadersChange = useCallback((val: string) => {
    setUserResponseHeaders(val);
  }, []);

  /**
   * 初始化数据
   */
  const loadData = async () => {
    const res = await getInterfaceInfoDetailByIdUsingGet({ id: Number(params.id) });
    setData(res.data);
    requestParamsInit = computeInitValue(res.data?.requestParams);
    requestHeadersInit = computeInitValue(res.data?.responseHeaders);
    setUserRequestParams(requestParamsInit);
    setUserRequestParams(requestParamsInit);
    setUserRequestHeaders(requestHeadersInit);
    setIsShownRequest(true);
  };
  useEffect(() => {
    loadData();
  }, []);

  return (
    <>
      <ProCard
        title="API开放平台"
        headStyle={{ textAlign: 'center' }}
        bodyStyle={{ fontSize: '15px' }}
        bordered
        direction="column"
        layout="center"
      >
        <h2>{data?.name}</h2>
        <h3>{data?.description}</h3>
      </ProCard>

      <PageContainer header={{ title: '' }}>
        <ProCard style={{ padding: 20 }} layout="center" direction="column">
          <Input.Search
            disabled={!verifyRes}
            addonBefore={
              <Tag
                bordered={false}
                color={data?.method?.toUpperCase() === 'GET' ? 'processing' : 'success'}
              >
                {data?.method}
              </Tag>
            }
            size="large"
            placeholder="请输入URL"
            value={data?.url}
            enterButton="发送"
            onSearch={async (text) => {
              console.log('text', text);
              try {
                setIsShownResponse(false);
                let res = await interfaceInfoCallUsingPost({
                  id: Number(data?.id),
                  userRequestParams: userRequestParams,
                });
                const result = JSON.stringify(
                  JSON.parse(res.data?.userResponseParams || ''),
                  null,
                  '\t',
                );
                setUserResponseParams(result);
                setIsShownResponse(true);
              } catch (error: any) {
                message.error(error.message ? error.message : '调用失败，请重试');
              }
            }}
            style={{ maxWidth: 522, width: '100%', margin: 'auto' }}
          />

          {/*请求*/}
          <Tabs
            size="large"
            centered
            defaultActiveKey="requestParams"
            style={{ width: '80%' }}
            items={[
              {
                key: 'requestParams',
                label: '请求参数',
                children: isShownRequest ? (
                  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                    <JsonInput
                      value={requestParamsInit}
                      onChange={onRequestParamsChange}
                      height="200px"
                      verifyRes={setVerifyRes}
                    />
                  </div>
                ) : null,
              },
              {
                key: 'requestHeaders',
                label: '请求头',
                children: isShownRequest ? (
                  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                    <JsonInput
                      value={requestHeadersInit}
                      onChange={onRequestHeadersChange}
                      height="200px"
                      verifyRes={setVerifyRes}
                    />
                  </div>
                ) : null,
              },
            ]}
          />

          {/*响应*/}
          {isShownResponse ? (
            <>
              <Tabs
                size="large"
                centered
                defaultActiveKey="responseParams"
                style={{ width: '80%' }}
                items={[
                  {
                    key: 'responseParams',
                    label: '响应参数',
                    children: (
                      <div
                        style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}
                      >
                        <JsonInput
                          value={userResponseParams}
                          onChange={onResponseParamsChange}
                          height="200px"
                        />
                      </div>
                    ),
                  },
                  {
                    key: 'responseHeaders',
                    label: '响应头',
                    children: (
                      <div
                        style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}
                      >
                        <JsonInput
                          value={userResponseHeaders}
                          onChange={onResponseHeadersChange}
                          height="200px"
                        />
                      </div>
                    ),
                  },
                ]}
              />
            </>
          ) : null}
        </ProCard>
      </PageContainer>
    </>
  );
};

export default AdvancedSearch;
